package com.hangoverstudios.batterysaver;


import java.lang.reflect.Method;
import java.util.Calendar;

import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.ToggleButton;

public class MainActivity extends Activity  {
	
	 int notifyID=1;
	
	
	Button powersave,wifi,brightness,dataconnection,gps,autoRotation,bluetooth,profile,battery_level;
    ToggleButton optim;
    Button save,cancel;

	SeekBar seekBar,seekBars;
    
    AudioManager mobilemode;
    
    ImageView charger;
    
    TextView charging;
    Helper helper;
    BroadcastReceiver batteryLevelReceiver;
    
    private StartAppAd startAppAd = new StartAppAd(this);
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		StartAppSDK.init(this, "109026838", "202627762", true);
		//StartAppAd.showSplash(this, savedInstanceState);
		setContentView(R.layout.activity_main);
		
		helper = new Helper(this);
		
		powersave=(Button)findViewById(R.id.button_power);
		wifi=(Button)findViewById(R.id.button_wifi);
		brightness=(Button)findViewById(R.id.button_brightness);
		dataconnection=(Button)findViewById(R.id.button_dataconnection);
		gps=(Button)findViewById(R.id.button_gps);
		autoRotation=(Button)findViewById(R.id.button_screenrotation);
		profile=(Button)findViewById(R.id.button_profile);
		bluetooth=(Button)findViewById(R.id.button_bluetooth);
		battery_level=(Button)findViewById(R.id.button_battery);
		optim=(ToggleButton)findViewById(R.id.button_optimize);
		save=(Button)findViewById(R.id.button_save);
		charging = (TextView)findViewById(R.id.txt_charging);
		
		getBatteryPercentage();
		
		if(helper.isPowerSaveModeOn())
		{
			optim.setBackgroundResource(R.drawable.button_press_round_green);
			optim.setText(optim.getTextOn());
		}
		else
		{
			optim.setBackgroundResource(R.drawable.button_press_round_red);
			optim.setText(optim.getTextOff());
		}
		
		if(Utils.getRingerMode(getApplicationContext()) == AudioManager.RINGER_MODE_NORMAL)
			profile.setText("Ring Mode");
		else if(Utils.getRingerMode(getApplicationContext()) == AudioManager.RINGER_MODE_SILENT)
			profile.setText("Silent Mode");
		else if(Utils.getRingerMode(getApplicationContext()) == AudioManager.RINGER_MODE_VIBRATE)
			profile.setText("Vibrate Mode");
     
		 if(Utils.isWifiEnabled(getApplicationContext()))
		 {
			wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_green, 0, 0);			
		 }
		 else
		 {
			wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_blue, 0, 0);			
		 }
	
		 if( !Utils.isBluetoothEnabled())
		 {   
			bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_blutooth, 0, 0);
		 }
		 else
		 { 
			bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_blutooth, 0, 0);
		 }
		 System.out.println("raj 11111111111");
		 
		 if( !Utils.isMobileDataEnabled(getApplicationContext()))
		 { 
			System.out.println("raj 2222222222222222");
	     	dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_arrow, 0, 0);
		 }
		 else			 
		 {
			System.out.println("raj 33333333333333");
		 	dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_arrow, 0, 0);
		 }
		 //raj profle mode
		 
		 if(android.provider.Settings.System.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0) == 1)
		 {
		     android.provider.Settings.System.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0);
			 autoRotation.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rotation_green, 0, 0);
	     }
	     else
	     {
	    	 android.provider.Settings.System.getInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
	    	 autoRotation.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rotation_blue, 0, 0);
	     }
		 setBatteryChecker(this);
	}
	
	public void onResume()
	{
		super.onResume();
		if(Utils.isGPSEnabled(getApplicationContext()))
			gps.setText("GPS ON");
		else
			gps.setText("GPS OFF");
		
		if( !Utils.isMobileDataEnabled(getApplicationContext()))
		 { 
			System.out.println("raj 2222222222222222");
	     	dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_arrow, 0, 0);
		 }
		 else			 
		 {
			System.out.println("raj 33333333333333");
		 	dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_arrow, 0, 0);
		 }
		
		startAppAd.onResume();
	}
	
	@Override
	public void onPause() {
	    super.onPause();
	    startAppAd.onPause();
	}
	
	public void setGPS(View view)
	{
		Utils.setgps(getApplicationContext());
	}
	
	public void setwifi(View view)
	{
		if(Utils.isWifiEnabled(getApplicationContext()))
		{
			Utils.setWIFIEnabled(getApplicationContext(), false);
			wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_blue, 0, 0);
		}
		else
		{

			Utils.setWIFIEnabled(getApplicationContext(), true);
			wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_green, 0, 0);
		}
	}
	public void setBluetooth(View view)
	{
		if(Utils.isBluetoothEnabled())
		{
			Utils.setBluetoothEnabled(false);
			bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_blutooth, 0, 0);
		}
		else
		{
			Utils.setBluetoothEnabled(true);
			bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_blutooth, 0, 0);
			
		}
	}
	
	public void togglePowerSaver(View view)
	{
		((ToggleButton) view).setChecked(!helper.isPowerSaveModeOn());
		if(((ToggleButton) view).isChecked())
		{
			helper.savePowerSaveModeEnabled(true);
			optim.setBackgroundResource(R.drawable.button_press_round_green);
			if(helper.isWifiSaverEnabled())
			{
				helper.saveWifiState(Utils.isWifiEnabled(getApplicationContext()));					
				Utils.setWIFIEnabled(getApplicationContext(), false);
				wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_blue, 0, 0);
				
			}
			if(helper.isBTSaverEnabled())
			{
				helper.saveBTState(Utils.isBluetoothEnabled());
				Utils.setBluetoothEnabled(false);
				bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_blutooth, 0, 0);
				
			}
			if(helper.isBrightnessSaverEnabled())
			{	
				int progress = 20;
				float brightness = progress / (float)255;
				WindowManager.LayoutParams lp = getWindow().getAttributes();
				        lp.screenBrightness = brightness;
				        getWindow().setAttributes(lp);
				android.provider.Settings.System.putInt(getContentResolver(),
						android.provider.Settings.System.SCREEN_BRIGHTNESS,
						progress);
			}

			if(helper.isVibrationSaverEnabled())
			{
				profile.setText("Vibrate Mode");
				helper.saveVibrationState(Utils.isDeviceInVibrateMode(getApplicationContext()));
				Utils.setDeviceMode(getApplicationContext(), AudioManager.RINGER_MODE_VIBRATE);
			}
			if(helper.isMobileDataSaverEnabled())
			{
				helper.saveMobileDataState(Utils.isMobileDataEnabled(getApplicationContext()));
				Utils.setMobileDataEnabled(getApplicationContext(), false);
				dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_arrow, 0, 0);
			}
		}
		else
		{
			helper.savePowerSaveModeEnabled(false);
			optim.setBackgroundResource(R.drawable.button_press_round_red);
			if(helper.isWifiSaverEnabled())
			{
				if(helper.getSavedWifiState())
				{
					Utils.setWIFIEnabled(getApplicationContext(), true);
					wifi.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.wifi_green, 0, 0);
				}
				
			}
			if(helper.isBTSaverEnabled())
			{
				if(helper.getSavedBTState())
				{
					Utils.setBluetoothEnabled(true);
					bluetooth.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_blutooth, 0, 0);
				}
				
			}
			if(helper.isBrightnessSaverEnabled())
			{	
				int progress = 20;
					android.provider.Settings.System.putInt(getContentResolver(),
							android.provider.Settings.System.SCREEN_BRIGHTNESS,
							progress);
			}

			if(helper.isVibrationSaverEnabled())
			{
				if(helper.getSavedVibrationState())
					Utils.setDeviceMode(getApplicationContext(), AudioManager.RINGER_MODE_NORMAL);
			}
			if(helper.isMobileDataSaverEnabled())
			{
				if(helper.getSavedMobileDataState())
				{
					Utils.setMobileDataEnabled(getApplicationContext(), true);
					dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_arrow, 0, 0);
				}
				
			}
		}
	}
	 public void setProfileMode(View v)
	 {
		 final Dialog dialog = new Dialog(this);
			dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			dialog.setContentView(R.layout.profile_options);
			ListView list_settings = (ListView)dialog.findViewById(R.id.list_settings);
			
			String[] list = {"Ring Mode", "Silent Mode", "Vibrate Mode"};
			
			final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.setting_item, list);
			
			list_settings.setAdapter(adapter);
			
			list_settings.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					
					if(position == 0)
					{
						profile.setText(adapter.getItem(position));
						Utils.setDeviceMode(getApplicationContext(), AudioManager.RINGER_MODE_NORMAL);
						Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
						final Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
						r.play();
						final Handler handler = new Handler();
						handler.postDelayed(new Runnable() {
						    public void run() {
						    	if(r.isPlaying())
						    		r.stop();
						    }
						}, 2000);
					}
					else if(position == 1)
					{
						profile.setText(adapter.getItem(position));
						Utils.setDeviceMode(getApplicationContext(), AudioManager.RINGER_MODE_SILENT);
					}					
					else
					{
						profile.setText(adapter.getItem(position));
						Utils.setDeviceMode(getApplicationContext(), AudioManager.RINGER_MODE_VIBRATE);
						Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
						v.vibrate(500);
					}
					dialog.dismiss();
				}
			});
			dialog.show();
			dialog.setCanceledOnTouchOutside(false);
	 }	
	 
	 
	public void powersave (View v){
		
		Intent i = new Intent(this,PowerSaveSettingsActivity.class);
	    startActivity(i);
	}
   public void dataconnection(View v)
   {
	   if(Utils.getDeviceAndroidVersion(getApplicationContext()) > 20)
		   setMobileData(getApplicationContext());
	   else
	   {
		   
		   if(Utils.isMobileDataEnabled(getApplicationContext()))
		   {
			   Utils.setMobileDataEnabled(getApplicationContext(), false);
			   dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.blue_arrow, 0, 0);
		   }
		   else 
		   {
			   Utils.setMobileDataEnabled(getApplicationContext(), true);
			   dataconnection.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.green_arrow, 0, 0);
		   }
	   }
   }
   public static void setMobileData(Context context)
	{
		 Intent mobileData = new Intent();
		 mobileData.setComponent(new ComponentName(
		            "com.android.settings",
		            "com.android.settings.Settings$DataUsageSummaryActivity"));
		//Intent mobileData = new Intent(Intent.ACTION_MANAGE_NETWORK_USAGE);	
		mobileData.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(mobileData);
	}
  public void autoRotation(View v)
  {  
	  if(android.provider.Settings.System.getInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0) == 1)
      {
		  android.provider.Settings.System.putInt(getContentResolver(),Settings.System.ACCELEROMETER_ROTATION, 0);
		  Toast.makeText(MainActivity.this, "Rotation OFF", Toast.LENGTH_SHORT).show();
		  autoRotation.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rotation_blue, 0, 0);
      }
      else
      {
    	  android.provider.Settings.System.putInt(getContentResolver(), Settings.System.ACCELEROMETER_ROTATION, 1);
		  Toast.makeText(MainActivity.this, "Rotation ON", Toast.LENGTH_SHORT).show();
		  autoRotation.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.rotation_green, 0, 0);
      }
    }
 
 
 public void setBrightness(View v){
	 
	 final Dialog dialog = new Dialog(this);
	 dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	 dialog.setContentView(R.layout.brightnessalert);
 
	 SeekBar brightness_level = (SeekBar)dialog.findViewById(R.id.brightness);
	 Button brightnessok = (Button)dialog.findViewById(R.id.button_adjust);
	 
	 brightnessok.setOnClickListener(new OnClickListener() {
		
		@SuppressLint("CommitPrefEdits")
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "Saved Successfully...", Toast.LENGTH_LONG).show();
			dialog.dismiss();
		}
	}); 
	
	 brightness_level.setMax(255);
	 
	 float curBrightnessValue = 0;
		try {
			curBrightnessValue = android.provider.Settings.System.getInt(
					getContentResolver(),
					android.provider.Settings.System.SCREEN_BRIGHTNESS);
		} catch (SettingNotFoundException e) {
			e.printStackTrace();
		}
		System.out.println("raj screen_brightness : "+curBrightnessValue);
		int screen_brightness = (int) curBrightnessValue;
		brightness_level.setProgress(screen_brightness);
		brightness_level.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			int progress = 0;
			@Override
			public void onProgressChanged(SeekBar seekBar, int progresValue,
					boolean fromUser) {
				progress = progresValue;
				float brightness = progress / (float)255;
				WindowManager.LayoutParams lp = getWindow().getAttributes();
				        lp.screenBrightness = brightness;
				        getWindow().setAttributes(lp);
						android.provider.Settings.System.putInt(getContentResolver(),
								android.provider.Settings.System.SCREEN_BRIGHTNESS,
								progress);
				System.out.println("raj progress : "+progress);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				android.provider.Settings.System.putInt(getContentResolver(),
						android.provider.Settings.System.SCREEN_BRIGHTNESS,
						progress);
			}
		});

		 dialog.show();
}
 
 
	// Method for battery Status //
   public void getBatteryPercentage() {
	   
	 batteryLevelReceiver = new BroadcastReceiver() {
		 
		 public void onReceive(Context context, Intent intent) {
			 
			String action = intent.getAction();
        	 
        	 if(Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction()))
        	 {
        		 int currentLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
                 int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
                 int level = -1;
                 if (currentLevel >= 0 && scale > 0) {
                     level = (currentLevel * 100) / scale;
                 }
                
                 battery_level.setText(""+level+"%");
                 if(level <= 20 )
                 {
                	 battery_level.setBackgroundResource(R.drawable.single_point);
                 }
                 else if(level <= 40 )
                 {
                	 battery_level.setBackgroundResource(R.drawable.double_point); 
                 }
                 else if(level <= 60 )
                 {
                	 battery_level.setBackgroundResource(R.drawable.three_point); 
                 }
                 else if(level <= 80 )
                 {
                	 battery_level.setBackgroundResource(R.drawable.four_point); 
                 }
                 else if(level <= 100 )
                 {
                	 battery_level.setBackgroundResource(R.drawable.full_battery); 
                 } 
        	 }
        	 if(Intent.ACTION_POWER_CONNECTED.equals(intent.getAction()))
        	 {
        		 charging.setVisibility(View.VISIBLE);
        	 }
        	 if(Intent.ACTION_POWER_DISCONNECTED.equals(intent.getAction()))
        	 {
        		 charging.setVisibility(View.GONE);
        	 }  
        	 
        	 int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        	 if(chargePlug == BatteryManager.BATTERY_PLUGGED_USB ||
        			 chargePlug == BatteryManager.BATTERY_PLUGGED_AC )
        	 {
        		 charging.setVisibility(View.VISIBLE);
        	 }
         }
     };
    
     IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
     batteryLevelFilter.addAction(Intent.ACTION_POWER_CONNECTED);
     batteryLevelFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
     registerReceiver(batteryLevelReceiver, batteryLevelFilter);
	 }
   
   public void setBatteryChecker(Context context)
   {
		Calendar cal = Calendar.getInstance(); 
		cal.set( cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), 
				cal.get(Calendar.DAY_OF_MONTH), Calendar.HOUR_OF_DAY, 0, 0);		
					
		cal.add(Calendar.MINUTE, 2);
		
		Intent myIntent = new Intent(context, BatteryService.class);
		myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent pendingIntent = PendingIntent.getService(context, 1021, myIntent,PendingIntent.FLAG_CANCEL_CURRENT);
		AlarmManager alarmManager = (AlarmManager)context.getSystemService(context.ALARM_SERVICE);
		alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*60*1, pendingIntent);
	}
   
   public void onDestroy()
   {
	   super.onDestroy();
	   if(batteryLevelReceiver != null)
		   unregisterReceiver(batteryLevelReceiver);
   }
   @Override
   public void onBackPressed() {
       startAppAd.onBackPressed();
       super.onBackPressed();
   }
 }
